<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %><jsp:useBean id="readingManager" scope="application" class="org.languageguide.readings.ReadingManager" /><html>
<head>
<%
	response.setHeader("Cache-Control","no-cache"); 
	response.setHeader("Pragma","no-cache"); 
	response.setDateHeader ("Expires", -1); 
	org.languageguide.user.User user = org.languageguide.user.UserManager.getUser(session);
	String readingIdStr = request.getParameter("id");
	
    Integer readingId = Integer.parseInt(readingIdStr);
    //String numberOfRows = "10";
    String target = request.getParameter("target");
	org.languageguide.readings.TranslatedReading reading = org.languageguide.readings.ReadingManager.getReading(readingIdStr, target);
	java.util.Collection<org.languageguide.readings.SentenceTranslation> sentenceTranslations =  readingManager.getSentenceTranslationList(readingId, target); 
	Integer numberOfRows =  sentenceTranslations.size();
	int lastParagraph = 0;
	java.util.List<Integer> list = new java.util.ArrayList<Integer>();
	java.util.List<java.util.List<Integer>> listOfLists = new java.util.ArrayList<java.util.List<Integer>>();
	int order = 1;
	for (org.languageguide.readings.SentenceTranslation translation: sentenceTranslations){ 
		int paragraph = translation.getParagraph();
		if (paragraph != lastParagraph){
			lastParagraph = paragraph;
			if (list.size() > 0){
				listOfLists.add(list);
			}
			list = new java.util.ArrayList<Integer>();
		}
		list.add(order);
		order++;
	}
	
	if (list.size() > 0){
		listOfLists.add(list);
	}
	
String redirectField      = "";
    if (user == null){
		user =	org.languageguide.user.UserManager.loginFromCookie(request);
		if (user== null){
			String query = request.getQueryString();
			System.out.println("query" + query);
			session.setAttribute("redirect_url", "../wiki/translate_reading.jsp?" + query);
			if (target != null){
					response.sendRedirect("../user/login.jsp?target=" + target);
			}
			else{
				response.sendRedirect("../user/login.jsp");
			}
			return;
		}
	}

%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Translate Sentences</title>
<script>
var paragraphs = <% out.print(listOfLists); %>;
var currentId;	
var arrayOfSentenceIndexesToTranslate;
var currentArrayIndex;

function translationParagraph(order){
	arrayOfSentenceIndexesToTranslate = paragraphs[order - 1];
	currentArrayIndex = 0;
	translateNext();
}

function translateNext(){
	currentId = arrayOfSentenceIndexesToTranslate[currentArrayIndex];
	var elem = document.getElementById("t" + currentId);
	translate(elem.innerHTML);
}

function translateText(response) {
	if (currentId != null){
		var elem = document.getElementById(currentId);
        var text = response.data.translations[0].translatedText;
		text = text.replace("&#39;", "'");
		elem.value =  text;
		elem.style.background= "pink";
		//value++;
		currentArrayIndex++;
		if (currentArrayIndex < arrayOfSentenceIndexesToTranslate.length){
			translateNext();
		}
	}
  }

function translate(toTranslate){
	var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    //var sourceText = escape(document.getElementById("sourceText").innerHTML);
      // WARNING: be aware that YOUR-API-KEY inside html is viewable by all your users.
      // Restrict your key to designated domains or use a proxy to hide your key
      // to avoid misuage by other party.
      var source = 'https://www.googleapis.com/language/translate/v2?key=AIzaSyDtujJfQf7WTn4TPnm99CwbVKWqPjQbu5E&source=en&target=<%= target %>&callback=translateText&q=' + toTranslate;
      newScript.src = source;

      // When we add this script to the head, the request is sent off.
      document.getElementsByTagName('head')[0].appendChild(newScript);
}


function up(value){
	var previousElem  =  document.getElementById(value - 1);
	if (previousElem.value != ""){
		alert("the text area above this one isn't empy");
		return
	}
	var elem =  document.getElementById(value++);
	while(elem != null){
		previousElem.value = elem.value;
		previousElem = elem;
		elem =  document.getElementById(value++);
	}

	//while (elem != null){
	
	//}
}

function down(value){
		//find the next blank text area
	var currentElem  =  document.getElementById(value++);
	var savedTranslation = currentElem.value;
	currentElem.value = "";
	var nextElem =  document.getElementById(value++);
	while (nextElem.value !== ""){
		var nextSaved = nextElem.value;
		nextElem.value = savedTranslation;
		savedTranslation = nextSaved;
		nextElem =  document.getElementById(value++);
	}
	nextElem.value = savedTranslation;
}
</script>
<% if (target.equals("ar")){ %>
<style>
	textarea{
		direction:rtl
	}
</style>
<% } %>

</head>

<body>
<form name="form1" method="post" onSubmit="return allowSubmit()" action="translate_reading_save.jsp">
  <table width="100%" border="0" cellpadding="3" cellspacing="1" align="center">
<% 
order = 0;
lastParagraph = 0;
for (org.languageguide.readings.SentenceTranslation translation: sentenceTranslations){ 
order++;
int paragraph = translation.getParagraph();
if (paragraph != lastParagraph){
lastParagraph = paragraph;
%>
<tr><td><button type="button" onClick="translationParagraph(<%= paragraph %>)">Google Translate Paragraph!</button></td></tr>
<%  }%>
			<tr><td><div id="t<%= order %>"><%= translation.getSentence() %></div></td><td>&nbsp;</td></tr>
			<tr><td>

				<textarea rows="3" cols="100" id="<%= order %>" name="<%= order %>"><%=translation.getTranslation() %></textarea>			

			</td><td><button onClick="up(<%= order %>)" type="button">Up</button> <button onClick="down(<%= order %>)" type="button">Down</button></td></tr>
<% } %>
 
 
  </table><br>
<div align="center"><br>
<%
boolean approved = reading.hasApprovedSentences();

String checkedStr;
if (approved){
	checkedStr = "checked";
}
else{
	checkedStr = "";
}
%>
<input name="approve_all" type="checkbox" value="all" <%= checkedStr %>>
Approve All Translations<br>

  <input type="submit" name="translation.submit" id="saveButton" value="Save" style="font-weight:bold; font-size: 120%">   <input type="submit" name="translation.submit"  value="Cancel" id="cancelButton" style="font-weight:bold; font-size: 120%; margin-left 20px;">
  </div>
  
  <input name="readingId" type="hidden" value="<%= readingId %>">
  <input name="target" type="hidden" value="<%= target %>">
    <input name="row_count" type="hidden" value="<%= numberOfRows %>">
 <%=  redirectField %>
 
</form>
</body>
</html>
